$(document).ready(function () {

    // 在ajax请求头中添加csrf_token保护
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            // 没有跨域且类型不属于以下四种类型才添加csrf_token
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader('X-CSRFToken', csrf_token);
            }
        }
    });

    $(document).ajaxError(function (event, request, settings) {
        let default_error_message = '服务端出错，请稍后重试。';
        let _message = null;
        if (request.status === 0){
            message('后台服务拒绝，请稍后重试。', 'error');
            return
        }
        if (request.responseJSON && request.responseJSON.hasOwnProperty('ertooltipror_msg')) {
            _message = request.responseJSON.error_msg;
        } else if (request.responseText) {
            let IS_JSON = true;
            let data = null;
            try {
                data = JSON.parse(request.responseText);
            }
            catch (err) {
                IS_JSON = false;
            }
            if (IS_JSON && data !== undefined && data.hasOwnProperty('error_msg')) {
                _message = JSON.parse(request.responseText).error_msg;
            } else {
                _message = default_error_message;
            }
        } else {
            _message = default_error_message;
        }
        message(_message, 'error');
    });

    // 事件绑定
    $btn_refresh_latest_report.on('click', function () {
        $.ajax({
            type: 'POST',
            url: '/ajax/report/latest/get',
            data: {},
            success: function (data, status, xhr) {
                if (data.error_no === 0){
                    $('.latest-report').remove();
                    $('.latest-report-dropdown-item-text').after(data.html_text);
                    message("已更新最新报告数据", "info");
                }else{
                     message("最新报告数据查询失败: " + data.error_msg, "error");
                }
            },
        });
    });

    // 为帮助按钮设置弹出框
    tippyHelpBtn();

});

let $btn_refresh_latest_report = $('#btn-refresh-latest-report');

function message(msg, type) {
    type = type || 'info';
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        // "positionClass": "toast-top-right",
        "positionClass": "toast-top-center",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    if (type === 'info'){
        toastr.info(msg);
    }
    else if (type === 'warning') {
        toastr.warning(msg);
    }
    else if (type === 'error') {
        toastr.error(msg);
    }
    else if (type === 'success') {
        toastr.success(msg);
    }
}

// 判断字符串是否是JSON格式
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            let obj=JSON.parse(str);
            if (typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }
        } catch(e) {
            console.log('error：'+str+'!!!'+e);
            return false;
        }
    }
    console.log('It is not a string!')
}

// 检查字符串中是否有HTML片段
function isHtml(htmlStr) {
    let  reg = /<[^>]+>/g;
    return reg.test(htmlStr);
}

// 判断对象类型
function whatIsIt(object) {
    let stringConstructor = "string".constructor;
    let arrayConstructor = [].constructor;
    let objectConstructor = ({}).constructor;

    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

// 等待元素加载出来(jQuery>3.0)
jQuery.wait = function (selector, func, times, interval) {
    // 参数
    // selector 选择器
    // func 加载出来后的回调函数
    // times 定时查询次数
    // interval 查询间隔
    let _times = times || -1, //100次
    _interval = interval || 20, //20毫秒每次
    _selector = selector, //选择器
    _self = $(_selector),
    _iIntervalID; //定时器id
    if( _self.length ){ //如果已经获取到了，就直接执行函数
        func && func(_self);
    } else {
        _iIntervalID = setInterval(function() {
            if(!_times) { //是0就退出
                clearInterval(_iIntervalID);
            }
            _times <= 0 || _times--; //如果是正数就 --

            _self = $(_selector); //再次选择
            if( _self.length ) { //判断是否取到
                func && func(_self);
                clearInterval(_iIntervalID);
            }
        }, _interval);
    }
    return this;
};

// 等待元素加载出来(jQuery<3.0)
// jQuery.fn.wait = function (func, times, interval) {
//     var _times = times || -1, //100次
//     _interval = interval || 20, //20毫秒每次
//     _self = this,
//     _selector = this.selector, //选择器
//     _iIntervalID; //定时器id
//     if( this.length ){ //如果已经获取到了，就直接执行函数
//         func && func.call(this);
//     } else {
//         _iIntervalID = setInterval(function() {
//             if(!_times) { //是0就退出
//                 clearInterval(_iIntervalID);
//             }
//             _times <= 0 || _times--; //如果是正数就 --
//
//             _self = $(_selector); //再次选择
//             if( _self.length ) { //判断是否取到
//                 func && func.call(_self);
//                 clearInterval(_iIntervalID);
//             }
//         }, _interval);
//     }
//     return this;
// };

// 为帮助按钮设置弹出框
function tippyHelpBtn() {
    let $helpBtn = $('.btn-help');
    tippy($helpBtn[0], {
        trigger: 'click',
        hideOnClick: true,
        placement: 'top',
        allowHTML: true,
        interactive: true,
        content: function (){
            return $helpBtn.next().html();
        },
        appendTo: () => document.body,
        zIndex: 200,
        theme: 'light',
        maxWidth: 'none',
    });
}